package okhttp.get;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Map;

/**
 * Get请求方式
 * Created by Niki on 2018/10/26 17:06
 */
public class GetDemo {
    public static void main(String[] args) {
        try {
            new GetDemo().json();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Get无参请求
     * @param url
     */
    private static void noParameter(String url) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("name", "niki")
                .addHeader("name","fangshuhao")
                .header("age", "26")
                .header("age","27")
                .build();

        final Headers headers = request.headers();
        headers.names().stream().forEach(s -> System.out.println("name:"+s+",value:"+headers.get(s)));
        System.out.println("***********************************");
        System.out.println(headers);
    }

    private final OkHttpClient client = new OkHttpClient();
    private final Moshi moshi = new Moshi.Builder().build();
    private final JsonAdapter<Gist> gistJsonAdapter = moshi.adapter(Gist.class);

    private  void json() throws IOException {
        Request request = new Request.Builder()
                .url("https://api.github.com/gists/c2a7c39532239ff261be")
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            Gist gist = gistJsonAdapter.fromJson(response.body().source());

            for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(entry.getValue().content);
            }
        }
    }

    static class Gist {
        Map<String, GistFile> files;
    }

    static class GistFile {
        String content;
    }
}
